import { R } from '@/components/axios/interface'
import lodash from 'lodash'
import serverApiUtils from '@/core/utils/serverApiUtils'
import { AxiosRequestConfig } from 'axios/index'
import http from '@/components/axios/http'
import PageResponse from '@/core/framework/types/model/response/PageResponse'
import AdminApiConfigDto from '@/core/framework/config/types/model/AdminApiConfigDto'

export type BaseAdminServerApiProps = {
	adminApiConfig: AdminApiConfigDto
}

class BaseAdminServerApi<Id, Response> {
	private adminApiConfig: AdminApiConfigDto

	constructor(params: BaseAdminServerApiProps) {
		this.adminApiConfig = params.adminApiConfig
	}

	getByIds = (token: string, ids: Id[]): Promise<R<Response[]>> => {
		const config = lodash.merge(
			{
				params: { ids: ids },
				headers: serverApiUtils.addOnlyTokenHeader(token),
			} as AxiosRequestConfig,
			serverApiUtils.convertApiConfig(this.adminApiConfig.list),
		)
		return http.post(config)
	}

	getById = (token: string, id: Id): Promise<R<Response>> => {
		const config = lodash.merge(
			{
				params: { ids: id },
				headers: serverApiUtils.addOnlyTokenHeader(token),
			} as AxiosRequestConfig,
			serverApiUtils.convertApiConfig(this.adminApiConfig.get),
		)
		return http.post(config)
	}

	search = (token: string, query?: string, page?: number, size?: number, sort?: string[]): Promise<R<PageResponse<Response>>> => {
		const config = lodash.merge(
			{
				params: { page: page, size: size, sort: sort },
				headers: serverApiUtils.addOnlyTokenHeader(token),
			} as AxiosRequestConfig,
			serverApiUtils.convertApiConfig(this.adminApiConfig.search),
		)
		return http.post(config)
	}

	add = (token: string, data: Response): Promise<R<Response>> => {
		const config = lodash.merge(
			{
				data: data,
				headers: serverApiUtils.addOnlyTokenHeader(token),
			} as AxiosRequestConfig,
			serverApiUtils.convertApiConfig(this.adminApiConfig.add),
		)
		return http.post(config)
	}

	modifyNotNullField = (token: string, data: Response): Promise<R<Response>> => {
		const config = lodash.merge(
			{
				data: data,
				headers: serverApiUtils.addOnlyTokenHeader(token),
			} as AxiosRequestConfig,
			serverApiUtils.convertApiConfig(this.adminApiConfig.modifyNotNullField),
		)
		return http.post(config)
	}

	removeLogic = (token: string, ids: Id[]): Promise<R<boolean>> => {
		const config = lodash.merge(
			{
				data: ids,
				headers: serverApiUtils.addOnlyTokenHeader(token),
			} as AxiosRequestConfig,
			serverApiUtils.convertApiConfig(this.adminApiConfig.removeLogic),
		)
		return http.post(config)
	}

	remove = (token: string, ids: Id[]): Promise<R<boolean>> => {
		const config = lodash.merge(
			{
				data: ids,
				headers: serverApiUtils.addOnlyTokenHeader(token),
			} as AxiosRequestConfig,
			serverApiUtils.convertApiConfig(this.adminApiConfig.remove),
		)
		return http.post(config)
	}
}

export default BaseAdminServerApi
